/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.wire.processors
{
	import org.etherframework.IEther;
	import org.etherframework.core.reflection.Accessor;
	import org.etherframework.core.reflection.MetadataMember;
	import org.etherframework.common.wire.IMetaProcessor;
	
	public final class Inject implements IMetaProcessor
	{
		private var _destroyed:Boolean;
		private var _members:Vector.<MetadataMember>;
		
		public function wire(target:Object, members:Vector.<MetadataMember>, ether:IEther):void
		{
			_members = members;
			
			for each (var member:MetadataMember in members)
			{
				if (member is Accessor && Accessor(member).access != "readwrite")
					throw new Error("Injection can be done only for readwrite members. " +
						"Member '" + member.name + "' of target " + target + " has " + 
						Accessor(member).access + ".");
				
				if (target.constructor == member.type)
					throw new Error("You can't use type " + member.type + 
						" for member '"+member.name+"' on object of the same type.");
				
				target[member.qualifiedName] = ether.dependencies.getInstance(member.type as Class);
			}
		}
		
		public function unwire(target:Object):void
		{
			for each (var member:MetadataMember in _members)
			{
				target[member.qualifiedName] = null;
			}
		}
		
		public function destroy():void
		{
		}
		
		public function get destroyed():Boolean { return _destroyed; }
		public function set destroyed(value:Boolean):void { _destroyed = value; }
	}
}